package com.shujia.scala

import scala.io.Source

object Demo27Join {
  def main(args: Array[String]): Unit = {

    //1、统计每个学生的总分【姓名，总分】

    //1、计算总分
    val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList

    //2、解析数据
    val idAndScore: List[(String, Int)] = scores
      .map(score => {
        val split: Array[String] = score.split(",")
        val id: String = split.head
        val sco: Int = split.last.toInt
        (id, sco)
      })

    //3、按照学号进行分组
    val groupByList: Map[String, List[(String, Int)]] = idAndScore
      .groupBy(kv => kv._1)

    //4、计算总分
    val sumScore: Map[String, Int] = groupByList
      .mapValues(value => value.map(kv => kv._2).sum)

    sumScore.foreach(println)

    //5、读取学生表
    val students: List[String] = Source.fromFile("data/students.txt").getLines().toList

    //6、取出学号和姓名
    val idAndName: List[(String, String)] = students
      .map(stu => {
        val split: Array[String] = stu.split(",")
        val id: String = split.head
        val name: String = split(1)
        (id, name)
      })


    //关联两个表
    //1、循环实现，时间复杂度是On**2
    for (scoreKv <- sumScore) {
      val id: String = scoreKv._1
      val sumSco: Int = scoreKv._2
      for (idNameKV <- idAndName) {
        val sid: String = idNameKV._1
        val name: String = idNameKV._2
        if (id.equals(sid)) {
          println(s"$id\t$name\t$sumSco")
        }
      }
    }

    //2、使用字典实现
    //循环学生表通过学号取总分表中获取总分
    val nameAndScore: List[(String, Int)] = idAndName
      .map(kv => {
        val id: String = kv._1
        val name: String = kv._2
        //通过学号获取总分
        val sumSco: Int = sumScore(id)
        (name, sumSco)
      })

    nameAndScore.foreach(println)

    println("=" * 100)

    //获取总分前十的学生
    val top10: List[(String, Int)] = nameAndScore.sortBy(kv => -kv._2).take(10)
    top10.foreach(println)
  }
}
